package util.tool;


import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
 * 简单的代理池
 * @author kong
 *
 */
public class ProxyPool implements Runnable {
//	public static void main(String[] args) {
//		ProxyPool pool = new ProxyPool();
//		for (int i = 0; i < 1000; i++) {
//			System.out.println(pool.count);
//			System.out.println(pool.getProxy());
//			try {
//				Thread.sleep(1000);
//			} catch (Exception e) {
//				// TODO: handle exception
//			}
//		}
//	}
	
	String[] proxyPool = null;
	int count = 0;
	public ProxyPool() {
		Thread thread=new Thread(this);
		thread.setDaemon(true);
		thread.start();
	}
	@Override
	/**
	 * 线程行为定义
	 */
	public void run() {
		try {
			String proxyJson = Requests.myGet("https://raw.githubusercontent.com/fate0/proxylist/master/proxy.list");
//			System.err.println(proxyJson);
			String[] res = proxyJson.split("\n");
			proxyPool = new String[res.length];
			for (int i = 0; i < res.length; i++) {
				JsonParser parser = new JsonParser();
				JsonObject json = (JsonObject)parser.parse(res[i]);
				Double aDouble = json.get("response_time").getAsDouble();
				if (aDouble > 2) continue;
				String host = json.get("host").getAsString() + ":" + json.get("port").getAsInt();
				
				try {
					System.err.println(host);
					// 测试一下代理
					Requests.myGet("http://baidu.com", null, host);
					proxyPool[count++] = host;
				} catch (Exception e) {
//					e.printStackTrace();
//					System.err.println("failed");
				}
			}
			
			
		} catch (Exception e) {
//			e.printStackTrace();
		}
//		System.out.println("done");
	}
	/**
	 * 开始维护代理池
	 */
	public void start() {
		Thread t = new Thread(this, "aaa");
		t.start();
	}
	/**
	 * 随机返回代理池中某一个ip
	 * @return 代理ip地址
	 */
	public String getProxy() {
		// 0_0
		if (proxyPool == null) return null;
		return proxyPool[(int) ((Math.random() * 19491001) % count)];
	}
}
